import pandas as pd
import utils.Model_Process as Model_Process


def predict_fault_probabilities(input_csv_file):
    # Load the saved model
    models = Model_Process.load_model("models/Steel_Plate_xgb.pkl")

    # Load the input data from CSV file
    input_data = pd.read_csv(input_csv_file)
    ids = input_data['id']
    input_data = input_data.drop(columns=["id"])

    # Initialize a DataFrame to store the predictions
    predictions = pd.DataFrame(index=input_data.index)

    # Predict probabilities for each target variable
    for target, model in models.items():
        predictions[target] = model.predict_proba(input_data)[:, 1]

    predictions.insert(0, 'id', ids.values)
    predictions.to_csv("data/fault/predictions.csv", index=False)

    return predictions

def calculate_fault_percentages(file_path, threshold_x):
# 读取CSV文件
    data = pd.read_csv(file_path)

    # 初始化计数器
    normal_count = 0
    fault_counts = {col: 0 for col in data.columns[1:]}

    # 遍历每一行数据
    for index, row in data.iterrows():
    # 检查是否超过阈值
        fault_types = [col for col in row.index[1:] if row[col] > threshold_x]
        if fault_types:
            # 如果有超过阈值的故障，选择概率最高的故障
            max_fault = max(fault_types, key=lambda x: row[x])
            fault_counts[max_fault] += 1
        else:
        # 如果没有超过阈值的故障，视为正常
            normal_count += 1

    # 计算总零件数
    total_parts = len(data)

    # 计算百分比
    normal_percentage = (normal_count / total_parts) * 100
    fault_percentages = {fault: (count / total_parts) * 100 for fault, count in fault_counts.items()}

    # 输出百分比
    return normal_percentage, fault_percentages

